import { ref, computed, watch, nextTick } from 'vue'

/**
 * 动态表单Hook
 * @param {Object} options 配置选项
 * @returns {Object} 表单相关方法和数据
 */
export function useDynamicForm(options = {}) {
  const {
    schema = [],
    model = {},
    config = {},
    events = {}
  } = options

  // 表单数据
  const formModel = ref({ ...model })
  
  // 表单引用
  const formRef = ref()
  
  // 表单状态
  const formState = ref({
    loading: false,
    submitting: false,
    errors: []
  })

  // 计算可见字段
  const visibleFields = computed(() => {
    return schema.filter(field => {
      if (typeof field.visible === 'function') {
        return field.visible(formModel.value)
      }
      return field.visible !== false
    })
  })

  // 计算显示字段
  const showFields = computed(() => {
    return visibleFields.value.filter(field => {
      if (typeof field.show === 'function') {
        return field.show(formModel.value)
      }
      return field.show !== false
    })
  })

  // 字段值变化处理
  const handleFieldChange = (field, value) => {
    // 更新表单数据
    formModel.value[field.field] = value
    
    // 触发联动
    handleFieldDependencies(field, value)
    
    // 触发事件
    if (events.onChange) {
      events.onChange(field.field, value, formModel.value)
    }
  }

  // 处理字段依赖关系
  const handleFieldDependencies = (changedField, value) => {
    // 查找依赖当前字段的其他字段
    const dependentFields = schema.filter(field => 
      field.dependencies && field.dependencies.includes(changedField.field)
    )
    
    // 触发依赖字段的重新计算
    dependentFields.forEach(field => {
      // 这里可以添加复杂的联动逻辑
      // 比如根据选择的值动态更新其他字段的选项
      if (events.onDependencyChange) {
        events.onDependencyChange(field, changedField, value, formModel.value)
      }
    })
  }

  // 表单验证
  const validate = async () => {
    try {
      formState.value.submitting = true
      const values = await formRef.value?.validateFields()
      formState.value.errors = []
      
      if (events.onValidate) {
        events.onValidate(true, [])
      }
      
      return { valid: true, values }
    } catch (errors) {
      formState.value.errors = errors
      
      if (events.onValidate) {
        events.onValidate(false, errors)
      }
      
      return { valid: false, errors }
    } finally {
      formState.value.submitting = false
    }
  }

  // 表单提交
  const submit = async () => {
    const { valid, values, errors } = await validate()
    
    if (valid) {
      if (events.onSubmit) {
        events.onSubmit(values)
      }
      return { success: true, data: values }
    } else {
      return { success: false, errors }
    }
  }

  // 表单重置
  const reset = () => {
    formRef.value?.resetFields()
    formModel.value = { ...model }
    formState.value.errors = []
    
    if (events.onReset) {
      events.onReset(formModel.value)
    }
  }

  // 设置字段值
  const setFieldValue = (field, value) => {
    formModel.value[field] = value
  }

  // 获取字段值
  const getFieldValue = (field) => {
    return formModel.value[field]
  }

  // 设置多个字段值
  const setFieldsValue = (values) => {
    Object.assign(formModel.value, values)
  }

  // 获取所有字段值
  const getFieldsValue = () => {
    return { ...formModel.value }
  }

  // 清除字段值
  const clearField = (field) => {
    delete formModel.value[field]
  }

  // 清除所有字段值
  const clearFields = () => {
    formModel.value = {}
  }

  // 监听表单数据变化
  watch(formModel, (newModel) => {
    if (events.onModelChange) {
      events.onModelChange(newModel)
    }
  }, { deep: true })

  return {
    // 数据
    formModel,
    formRef,
    formState,
    visibleFields,
    showFields,
    
    // 方法
    handleFieldChange,
    validate,
    submit,
    reset,
    setFieldValue,
    getFieldValue,
    setFieldsValue,
    getFieldsValue,
    clearField,
    clearFields
  }
} 